//
//  LLHomeController.m
//  Weibo
//
//  Created by 李灵斌 on 15-1-28.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "LLHomeController.h"
#import "LLTitleView.h"
#import "LLPopView.h"
#import "LLPopViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "LLScanTableViewController.h"
#import "LLDefaultView.h"
#import "LLLoadMoreView.h"
@interface LLHomeController ()
@property (nonatomic, strong) NSMutableArray *statuses;
@property (nonatomic, weak) UIRefreshControl *refresh;
@end

@implementation LLHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // 创建导航条的BarButtonItem
    [self setupNavBar];
    
    // 获取用户数据
    if (self.defaultView != nil) {
//        self.defaultView.iconView.image = [UIImage imageNamed:@"visitordiscover_image_home"];;
        self.defaultView.contentLab.text = @"当你关注一些人以后，他们发布的最新消息会显示在这里";
    } else {
        
        [self setupUserInfo];
        // 获取微博数据

        // 添加上拉加载按钮
        [self setupRefresh];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 开始旋转
    [self.defaultView startRotate];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 停止旋转
    [self.defaultView endRotate];
}

#pragma mark - 网络请求获取数据
/**
 *  获取用户数据
 */
- (void)setupUserInfo{
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    LLAccount *account = [LLAccountTool readInShaHe];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    para[@"access_token"] = account.access_token;
    para[@"uid"] = account.uid;
    [mgr GET:@"https://api.weibo.com/2/users/show.json" parameters:para success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *userIcon = responseObject[@"profile_image_url"];
        if ([account.profile_image_url isEqualToString:userIcon]) {
            return;
        }
        account.profile_image_url = userIcon;
        [LLAccountTool save:account];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}


#pragma mark - 上拉加载按钮
- (void)setupRefresh{
    
//    UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
//    [self.tableView addSubview:refresh];
//    self.refresh = refresh;
//    [refresh beginRefreshing];
//    // 监听按钮值改变事件
//    [refresh addTarget:self action:@selector(loadNewStatus:) forControlEvents:UIControlEventValueChanged];
//    [self loadNewStatus:refresh];
//    
//    // 设置下拉加载更多
//    LLLoadMoreView *footerView = [LLLoadMoreView loadMoreView];
//    footerView.height = 44;
//    self.tableView.tableFooterView = footerView;
//    self.tableView.tableFooterView.hidden = YES;
    [self.tableView addHeaderWithTarget:self action:@selector(loadNewStatus)];
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreDate)];
    [self.tableView headerBeginRefreshing];
}

/**
 *  加载更新的微博数据
 */
- (void)loadNewStatus{
    
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    LLAccount *account = [LLAccountTool readInShaHe];
    para[@"access_token"] = account.access_token;
    NSString *idstr = [[self.statuses firstObject] idstr];
    if (idstr != nil) {
        para[@"since_id"] = idstr;
    }
    [mgr GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"%@", responseObject);
        NSArray *newArray = responseObject[@"statuses"];
        NSArray *models = [LLStatus objectArrayWithKeyValuesArray:newArray];
        
        //        [self.statuses addObjectsFromArray:models];
        NSRange range = NSMakeRange(0, models.count);
        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statuses insertObjects:models atIndexes:set];
        [self.tableView reloadData];
        
        // 添加提示控件
        [self setupTipInfo:models.count];
//        self.tableView.tableFooterView.hidden = YES;
        [self.tableView headerEndRefreshing];
//        [refresh endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        [refresh endRefreshing];
        [self.tableView headerEndRefreshing];
    }];
//    [mgr GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:para success:^(NSURLSessionDataTask *task, id responseObject) {
//                NSLog(@"%@", responseObject);
//        
//        NSArray *newArray = responseObject[@"statuses"];
//        NSArray *models = [LLStatus objectArrayWithKeyValuesArray:newArray];
//        
////        [self.statuses addObjectsFromArray:models];
//        NSRange range = NSMakeRange(0, models.count);
//        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
//        [self.statuses insertObjects:models atIndexes:set];
//        [self.tableView reloadData];
//        
//        // 添加提示控件
//        [self setupTipInfo:models.count];
//        
//        [refresh endRefreshing];
//        
//    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        [refresh endRefreshing];
//    }];
}

/**
 *  加载更多数据
 */
- (void)loadMoreDate{
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    LLAccount *account = [LLAccountTool readInShaHe];
    para[@"access_token"] = account.access_token;
    NSString *idstr = [[self.statuses lastObject] idstr];
    if (idstr) {
        para[@"max_id"] = @([idstr longLongValue] - 1);
    }
    [mgr GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:para success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSArray *newArray = responseObject[@"statuses"];
        NSArray *models = [LLStatus objectArrayWithKeyValuesArray:newArray];
        [self.statuses addObjectsFromArray:models];
         [self.tableView reloadData];
//        self.tableView.tableFooterView.hidden = YES;
        [self.tableView footerEndRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        self.tableView.tableFooterView.hidden = YES;
        [self.tableView footerEndRefreshing];
    }];
}

#pragma mark - 添加提示控件
- (void)setupTipInfo:(NSUInteger)count{
    
    UILabel *tipLab = [[UILabel alloc] init];
    [self.navigationController.view insertSubview:tipLab belowSubview:self.navigationController.navigationBar];
    tipLab.x = 0;
    tipLab.width = self.view.width;
    tipLab.height = 25;
    tipLab.font = [UIFont systemFontOfSize:14];
    tipLab.textColor = [UIColor whiteColor];
    tipLab.y = 64 - tipLab.height;
    tipLab.backgroundColor = [UIColor orangeColor];
    tipLab.textAlignment = NSTextAlignmentCenter;
    tipLab.text = [NSString stringWithFormat:@"共有%tu条❤️消息", count];
    
    [UIView animateWithDuration:1.0 animations:^{
        tipLab.transform = CGAffineTransformMakeTranslation(0, tipLab.height);
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:1 delay:1 options:0 animations:^{
            tipLab.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [tipLab removeFromSuperview];
        }];
    }];
}

#pragma mark - 导航条上item创建和点击事件
/**
 *  创建导航条的BarButtonItem
 */
#warning 为什么用UIButton
- (void)setupNavBar{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_friendsearch" higImage:@"navigationbar_friendsearch_highlighted" action:@selector(friendsearchClick) target:self];
    
    UIBarButtonItem *popItem = [UIBarButtonItem itemWithImage:@"navigationbar_pop" higImage:@"navigationbar_pop_highlighted" action:@selector(popClick) target:self];
    self.navigationItem.rightBarButtonItem = popItem;
    
    
    LLTitleView *titleView = [[LLTitleView alloc] init];
    [titleView setTitle:@"首页" image:@"navigationbar_arrow_down" selectImage:@"navigationbar_arrow_up"];
    [titleView sizeToFit];
    self.navigationItem.titleView = titleView;
    [titleView addTarget:self action:@selector(titleViewClick:) forControlEvents:UIControlEventTouchUpInside];
    
}

//static UIWindow *window;
// titleViewClick
- (void)titleViewClick:(LLTitleView *)titleView{
    
    titleView.selected = !titleView.selected;

    
    LLPopViewController *popVc = [[LLPopViewController alloc ]init];
    popVc.view.size = CGSizeMake(120, 160);
    // 创建popView
    [LLPopView popViewForView:titleView contentVc:popVc dismiss:^{
        
        titleView.selected = !titleView.selected;
        
        
    }];
}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];

}

// leftBarButtonItem 点击
- (void)popClick{
    
//    LLScanTableViewController *scanTVC = [[LLScanTableViewController alloc] init];
//    scanTVC.view.size = CGSizeMake(80, 50);
//    
//    [LLPopView popViewForView:self.navigationController.navigationBar.subviews[2] contentVc:scanTVC dismiss:^{
//        
//        
//    } type:LLPopViewTypeRight];
    // 二维码扫描
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"LLScanViewController" bundle:nil];
    UITabBarController *tabBarVc = [sb instantiateInitialViewController];
    
    [self presentViewController:tabBarVc animated:YES completion:nil];
}

// rightBarButtonItem 点击
- (void)friendsearchClick{
    
}

#pragma mark - 懒加载
- (NSMutableArray *)statuses{
    
    if (!_statuses) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}

#pragma mark - 数据源 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.statuses.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *ID = @"homeCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    
    LLStatus *status = self.statuses[indexPath.row];
    LLUser *user = status.user;
    cell.textLabel.text = user.name;
    cell.detailTextLabel.text = status.text;
    cell.imageView.layer.cornerRadius = 22;
    cell.imageView.layer.masksToBounds = YES;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:user.profile_image_url] placeholderImage:[UIImage imageNamed:@"avatar_default_big"]];
    
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (self.statuses.count == 0 ||
        self.tableView.tableFooterView.hidden == NO) {
        return;
    }
    CGFloat height = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.size.height;
    CGFloat offY = scrollView.contentOffset.y;
    
    if (offY >= height) {
        
        self.tableView.tableFooterView.hidden = NO;
        [self loadMoreDate];
    }
}


@end
